package com.konne.nightmare.FastPublicOpinion.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;

import com.konne.nightmare.FastPublicOpinion.R;

/**
 * Create by ws.
 * on Data:2022/2/12  Time:下午 5:58.
 * description: 虚线 .
 */
public class DashLineView extends View {

    private Context context;
    private Paint paint = new Paint();
    private int orientation = 0;
    private int lineColor;
    private int lineSpace;
    private int blankSpace;
    private Path path = new Path();

    public DashLineView(Context context) {
        this(context, null);
    }

    public DashLineView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public DashLineView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
        initAttrs(attrs);
        init();
    }

    private void initAttrs(AttributeSet attrs){
        if(attrs==null){
            return;
        }
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.DashLineView);
        orientation = typedArray.getInteger(R.styleable.DashLineView_orientation, 0);
        lineColor = typedArray.getInteger(R.styleable.DashLineView_line_color, Color.WHITE);
        lineSpace = typedArray.getDimensionPixelOffset(R.styleable.DashLineView_line_space, dp2px(5));
        blankSpace = typedArray.getDimensionPixelOffset(R.styleable.DashLineView_blank_space, dp2px(5));
    }

    private void init(){
        paint.setColor(lineColor);
        paint.setAntiAlias(true);
        paint.setStyle(Paint.Style.STROKE);
        //绘制长度为lineSpace的实线后再绘制长度为blankSpace的空白区域，0位间隔
        paint.setPathEffect(new DashPathEffect(new float[]{lineSpace, blankSpace}, 0));

        post(new Runnable() {
            @Override
            public void run() {
                //设置画笔宽度
                if(orientation==0) { //水平
                    paint.setStrokeWidth(getMeasuredHeight());
                }else{
                    paint.setStrokeWidth(getMeasuredWidth());
                }
            }
        });
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        path.moveTo(0, 0);
        if(orientation==0){ //水平
            path.lineTo(getWidth(), 0);
        }else{ //垂直
            path.lineTo(0, getHeight());
        }
        canvas.drawPath(path, paint);
    }

    /** dp转px */
    public int dp2px(float dpVal){
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,dpVal, context.getResources().getDisplayMetrics());
    }
}
